export const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1

export const isIPhone = navigator.userAgent.indexOf('iPhone') > -1

export const isIPad = navigator.userAgent.indexOf('iPad') > -1

export const isIPod = navigator.userAgent.indexOf('iOS') > -1

export const isWeChat = navigator.userAgent.indexOf('MicroMessenger') > -1

export const isQQ = navigator.userAgent.indexOf(' QQ') > -1
//转换json格式
export const isJSON = s => {
    try {
        JSON.parse(s)
    } catch (e) {
        return false
    }
    return true
}

// 延迟的防抖动函数 当持续触发事件时，一定时间段内没有再触发事件，事件处理函数才会执行一次，如果设定的时间到来之前，又一次触发了事件，就重新开始延时，知道用户不在触发后的一定时间内才执行该处理函数。
export const debounce = (callback, delay = 1000) => {
    let timer
    return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
        callback.apply(this, arguments)
        }, delay)
    }
}

//节流是将多次执行变成每隔一段时间执行，即n秒内只执行一次
export const throttle = (func, delay = 1000 ) =>{
    let canRun=true
    return function(){
        if(!canRun) return
        canRun=false
        setTimeout(() => {
            func.apply(this,arguments)
            canRun=true
        }, delay)
    }
}

//'x'.padStart(5, 'ab') // 'ababx' 字符串补全长度
export const formatNumber = number => String(number).padStart(2, '0')

//四舍五入小数点后几位数
export const formatMoney = money => Number(money).toFixed(2)

//时间戳转换事件
export const formatDate = date => {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()

    return [year, month, day].map(formatNumber).join('-')
}

export const formatTime = date => {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//复制
export const copyToClipboard = s => {
    console.log(s)
    let isSuccess = false
    let input = document.createElement('input')
    input.setAttribute('readonly', 'readonly')
    input.setAttribute('value', s)
    document.body.appendChild(input)
    input.select()
    input.setSelectionRange(0, input.value.length)
    if (document.execCommand('copy')) {
        document.execCommand('copy')
        isSuccess = true
    }
    document.body.removeChild(input)
    return isSuccess
}

//居中
export const resizeGameStage = $el => {
    let widthRatio = window.innerWidth / 375
    let heightRatio = window.innerHeight / 667
    let positionTop = (window.innerHeight - 667) * 0.5
    let positionLeft = (window.innerWidth - 375) * 0.5

    $el.style = `
        position: fixed;
        top: ${positionTop}px;
        left: ${positionLeft}px;
        transform: scale(${Math.min(widthRatio, heightRatio)});
    `
}

// 图片压缩
export const imageCompress = (file, quality = 0.7, success, error) => {
    // 小于512K不压缩
    if (file.size < 524288) {
        success(file)
        return
    }

    const name = file.name // 文件名
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
        const src = e.target.result

        const img = new Image()
        img.src = src
        img.onload = (e) => {
            const w = img.width
            const h = img.height
            // 生成canvas
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            // 创建属性节点
            const anw = document.createAttribute('width')
            anw.nodeValue = w
            const anh = document.createAttribute('height')
            anh.nodeValue = h
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)

            // 铺底色 PNG转JPEG时透明区域会变黑色
            ctx.fillStyle = '#fff'
            ctx.fillRect(0, 0, w, h)

            ctx.drawImage(img, 0, 0, w, h)
            // quality值越小，所绘制出的图像越模糊
            const base64 = canvas.toDataURL('image/jpeg', quality) // 图片格式jpeg或webp可以选0-1质量区间

            // 返回base64转blob的值
            // console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`)
            // 去掉url的头，并转换为byte
            const bytes = window.atob(base64.split(',')[1])
            // 处理异常,将ascii码小于0的转换为大于0
            const ab = new ArrayBuffer(bytes.length)
            const ia = new Uint8Array(ab)
            for (let i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i)
            }
            file = new Blob([ab], {type: 'image/jpeg'})
            file.name = name

            success(file)
        }
        img.onerror = (e) => {
            error('error')
        }
    }
    reader.onerror = (e) => {
        error('error')
    }
}

//HTML和JavaScript读写本地文件
export const blobToFile = (theBlob) => {
    let file = new File([theBlob], theBlob.name, {type: theBlob.type})
    return file
}
